package org.example.aaaatest.urlPost;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;

/**
 * @description:
 * @author: wangbaogui
 * @create: 2025/2/6 17:25
 **/
@Slf4j
public class urlPostTest {


    /**
     * 发送POST请求(调用辱骂和不文明语使用)
     *
     * @param restTemplate
     * @param url
     * @param request
     * @param responseType
     * @param <T>订单
     * @param <R>
     * @return
     */
    public static <T, R> R postRequest(RestTemplate restTemplate, String url, T request, Class<R> responseType) {
        try {
            String requestBody = JSON.toJSONString(request);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 3. 构建HTTP请求
            HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);

            // 4. 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    url,
                    HttpMethod.POST,
                    entity,
                    String.class // 返回原始字符串
            );
            String responseBody = response.getBody();

            log.info("Raw response: {}", JSON.toJSONString(responseBody));

            if (responseBody == null) {
                return null;
            }

            // 5. 反序列化响应
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(responseBody, responseType);

        } catch (Exception e) {
            log.error("HTTP request failed. Error: {}", e.getMessage(), e);
            return null;
        }
    }

}
